package de.hwr.chronix.client.alt;


import java.util.ArrayList;
import java.util.Date;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiField;
import com.bradrydzewski.gwt.calendar.client.Appointment;
import com.bradrydzewski.gwt.calendar.client.AppointmentStyle;
import com.bradrydzewski.gwt.calendar.client.Calendar;
import com.bradrydzewski.gwt.calendar.client.CalendarViews;
import com.bradrydzewski.gwt.calendar.client.event.TimeBlockClickEvent;
import com.bradrydzewski.gwt.calendar.client.event.TimeBlockClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.event.dom.client.ChangeEvent;

import de.hwr.chronix.shared.Attendee;
import de.hwr.chronix.shared.Poll;
import de.hwr.chronix.shared.TimeslotAdmin;
import de.hwr.chronix.shared.TimeslotAttendee;

public class Formular_Slotwahl extends Composite {

	private static Formular_SlotwahlUiBinder uiBinder = GWT
			.create(Formular_SlotwahlUiBinder.class);
	@UiField
	Calendar calwid_calendar;
	@UiField
	ListBox lb_dates;
	@UiField
	Button b_timeslots_uebernehmen;

	private ArrayList<String> datelist = new ArrayList<String>();
	private ArrayList<TimeslotAttendee> timeslots = new ArrayList<TimeslotAttendee>();	
	private Poll poll;
	
	interface Formular_SlotwahlUiBinder extends
			UiBinder<Widget, Formular_Slotwahl> {
	}
					
	public Formular_Slotwahl(Poll p) {
		initWidget(uiBinder.createAndBindUi(this));
		calwid_calendar.setView(CalendarViews.DAY, 1);
		poll=p;
		for (TimeslotAdmin tsa : poll.getTimeslotAdmins()) {
			datelist.add(tsa.getStart().getDate()+"."+(tsa.getStart().getMonth()+1)+"."+(tsa.getStart().getYear()+1900));	
		}
		this.addDatestoListbox();
		this.setCalendarFocus();
		this.setHandler();
		
		for (TimeslotAdmin tad:poll.getTimeslotAdmins()){
			int[] busytimes = new int[48];
			String[] busytimesAttendees = new String[48];
			this.generateBusytimes(busytimes,busytimesAttendees,tad);
			this.createAppointments(busytimes,busytimesAttendees, tad);
		}

	}
	

	private void addDatestoListbox() {
		// TODO Auto-generated method stub
		for (String date : datelist) {
			lb_dates.addItem(date);
			
		}
	}
	
	private void setHandler() {
		calwid_calendar
				.addTimeBlockClickHandler(new TimeBlockClickHandler<Date>() {
					@Override
					public void onTimeBlockClick(TimeBlockClickEvent<Date> event) {
						Date startDate = event.getTarget();
						Date endDate = (Date) startDate.clone();

						endDate.setHours(endDate.getHours() + 1);
						Appointment appointment = new Appointment();
						appointment.setStart(startDate);
						appointment.setEnd(endDate);
						appointment.setTitle("Your Timeslot");
						appointment.setStyle(AppointmentStyle.GREEN);
						calwid_calendar.addAppointment(appointment);
					
//						TimeslotAttendee timeslot= new TimeslotAttendee(appointment.getStart(),appointment.getEnd());
//						timeslots.add(timeslot);
					}
				});
	}

	private void setCalendarFocus() {
		calwid_calendar.setDate(this.convertStringDate(lb_dates.getItemText(lb_dates.getSelectedIndex())));
	}

	private Date convertStringDate(String dateString) {
		int day = Integer.parseInt(dateString.substring(0, 2));
		int month = Integer.parseInt(dateString.substring(3, 5)) - 1;
		int year = Integer.parseInt(dateString.substring(6, 10)) - 1900;
		Date date = new Date(year, month, day);
		return date;
	}

	@UiHandler("lb_dates")
	void onLb_datesChange(ChangeEvent event) {
		this.setCalendarFocus();
	}

	@UiHandler("b_timeslots_uebernehmen")
	void onB_timeslots_uebernehmenClick(ClickEvent event) {
		for(Appointment allappointments : calwid_calendar.getAppointments()){
			if (allappointments.getTitle().compareTo("Your Timeslot")==0){
				poll.addTimeslotAttendee(this.loadintoTimeslotAttendee(allappointments));
			}
		}
		
		for(Appointment allappointments : calwid_calendar.getAppointments()){
			System.out.println(allappointments.getTitle());
		}
		
			
		
	}

	
	

	private TimeslotAttendee loadintoTimeslotAttendee(Appointment appointment) {
		// TODO Auto-generated method stub
		TimeslotAttendee ta = new TimeslotAttendee();
		ta.setPoll(poll);
		ta.setStart(appointment.getStart());
		ta.setEnd(appointment.getEnd());
		ta.setAttendee(new Attendee());
		return ta;

	}


	private void generateBusytimes(int[] busytimes, String[] busytimesAttendees, TimeslotAdmin tad) {
		// TODO Auto-generated method stub
		for (TimeslotAttendee ts: poll.getTimeslotAttendees()){
			if(this.sameDay(ts.getStart(),tad.getStart())==0){
					
				int hours = ts.getStart().getHours();
				int minutes = ts.getStart().getMinutes();
				int additionalindex = 0;
				if (minutes==0) {additionalindex=0;}
				if (minutes==40) {additionalindex=1;}
				int startindex= (hours*2-1)+additionalindex;
				int endhours = ts.getEnd().getHours();
				int endminutes = ts.getEnd().getMinutes();
				int dif_hours= endhours-hours;
				int dif_minutes= endminutes-minutes;
				
				int endindex = (int) ((dif_hours/0.5)+(dif_minutes/30));
			
				for (int j=0;  j< endindex ; j++) {
					if (busytimes[startindex]==0){
						busytimesAttendees[startindex]=ts.getAttendee().getName();
					}else{
						busytimesAttendees[startindex]=(busytimesAttendees[startindex]+", "+ts.getAttendee().getName());
					}
					busytimes[startindex]=busytimes[startindex]+1;
					
					System.out.println(busytimesAttendees[startindex]);
					startindex++;
				}
			}
		
//			for (int i = 0; i < busytimes.length; i++) {
//				System.out.print("Index: ");
//				System.out.print(i);
//				System.out.print("Inhalt: ");
//				System.out.println(busytimes[i]);
//			}
		}
	}
	
	private void createAppointments(int[] busytimes, String[] busytimesAttendees, TimeslotAdmin tad) {
		// TODO Auto-generated method stub
		for (int k=0; k<busytimes.length;k++){
			if (busytimes[k]>0){
				Appointment appointment = new Appointment();
				appointment.setTitle(busytimesAttendees[k]);
				
				int hour= (k+1)/2;
				int minutesindex=(k+1)%2;
				int min = 0;
				if (minutesindex==0) {min=0;}
				if (minutesindex==1) {min=30;}
				
				Date start = (Date) tad.getStart().clone();
				start.setHours(hour);
				start.setMinutes(min);
				appointment.setStart(start);
				
				int i=1;
				while (busytimes[k]==busytimes[k+i]){
					k++;
				}
							
				hour= (k+1)/2;
				minutesindex=(k+1)%2;
				min = 0;
				if (minutesindex==0) {min=0;}
				if (minutesindex==1) {min=30;}
				
				Date end = (Date) tad.getEnd().clone();
				if (min<30){min=min+30;}else{min=min-30;hour=hour+1;}
						
				end.setHours(hour);
				end.setMinutes(min);
				appointment.setEnd(end);
				this.setAppointmentStyle(appointment, busytimes[k]);
				calwid_calendar.addAppointment(appointment);
			}
		}
	}

	private void setAppointmentStyle(Appointment appointment, int anzahl) {
		// TODO Auto-generated method stub
		
		if (anzahl==1){
			appointment.setStyle(AppointmentStyle.BLUE_GREY);
		}else{
			if (anzahl==2){
				appointment.setStyle(AppointmentStyle.LIGHT_TEAL);
			}else{
				if (anzahl==3){
					appointment.setStyle(AppointmentStyle.BLUE);
				}else{
					appointment.setStyle(AppointmentStyle.STEELE_BLUE);
				}
			}
		}
	}
	
	private int sameDay(Date start, Date date) {
		// TODO Auto-generated method stub
		if (start.getYear()==date.getYear() && start.getMonth()==date.getMonth() && start.getDate()==date.getDate()){
			return 0;
		}else {
			return -1;
		}
	}
}

